import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:member_center_sdk/core/sdk_enum.dart';
import 'package:member_center_sdk/sdk.dart';
import 'package:member_center_sdk_example/core/auth_type.dart';
import 'action.dart';
import 'state.dart';

Effect<SetPasswordBySmsState> buildEffect() {
  return combineEffects(<Object, Effect<SetPasswordBySmsState>>{
    SetPasswordBySmsAction.sendSms: _onSendSmsAction,
    SetPasswordBySmsAction.setPassword: _onSetPasswordAction,
  });
}

Future _onSendSmsAction(
    Action action, Context<SetPasswordBySmsState> ctx) async {
  var sdk = MemberCenterSdk.get();
  ctx.dispatch(SetPasswordBySmsActionCreator.onSetRemainAction(120));
  ctx.dispatch(SetPasswordBySmsActionCreator.onLoadingAction(true));
  var sdkResult = await sdk.sendSms(SmsType.Auth, ctx.state.phone);
  ctx.dispatch(SetPasswordBySmsActionCreator.onLoadingAction(false));
  if (sdkResult.success) {
    sdk.setCacheUserName(1, ctx.state.phone);
    ctx.dispatch(SetPasswordBySmsActionCreator.onSetSmsId(sdkResult.smsId));
    Fluttertoast.showToast(msg: "发送成功");
  } else {
    Fluttertoast.showToast(msg: sdkResult.message);
  }
  ctx.dispatch(
      SetPasswordBySmsActionCreator.onSetRemainAction(sdkResult.remainSeconds));
}

Future _onSetPasswordAction(
    Action action, Context<SetPasswordBySmsState> ctx) async {
  if (ctx.state.smsId == null) {
    Fluttertoast.showToast(msg: "请先发送短信");
    return;
  }
  var password = ctx.state.passwordController.text;
  if (password == null || password.isEmpty) {
    Fluttertoast.showToast(msg: "请填写密码");
    return;
  }
  String code = ctx.state.codeController.text;
  var sdk = MemberCenterSdk.get();
  var sdkResult = await sdk.setPassword(
      AuthType.login.index, "", ctx.state.smsId, code, password);
  if (sdkResult.success) {
    if (sdkResult.value == true) {
      Fluttertoast.showToast(msg: "设置密码成功");
      Navigator.of(ctx.context).pop(true);
    } else {
      Fluttertoast.showToast(msg: "设置密码失败");
    }
  } else {
    Fluttertoast.showToast(msg: sdkResult.message);
  }
}
